import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { ThemeType } from '@shared/types';
import { THEMES } from '@shared/constants';

interface ThemeState {
  theme: ThemeType;
  systemTheme: 'light' | 'dark';
  setTheme: (theme: ThemeType) => void;
  toggleTheme: () => void;
  getEffectiveTheme: () => 'light' | 'dark';
  initTheme: () => void;
}

export const useThemeStore = create<ThemeState>()(
  persist(
    (set, get) => ({
      theme: 'light',
      systemTheme: 'light',

      setTheme: (theme: ThemeType) => {
        set({ theme });
        // 通知主进程主题变化
        if (window.electronAPI) {
          window.electronAPI.theme.set(theme);
        }
        // 应用主题到CSS变量
        applyTheme(theme === 'auto' ? get().systemTheme : theme);
      },

      toggleTheme: () => {
        const currentTheme = get().theme;
        const newTheme = currentTheme === 'light' ? 'dark' : 'light';
        get().setTheme(newTheme);
      },

      getEffectiveTheme: () => {
        const { theme, systemTheme } = get();
        return theme === 'auto' ? systemTheme : theme;
      },

      initTheme: () => {
        // 检测系统主题
        const detectSystemTheme = () => {
          if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            return 'dark';
          }
          return 'light';
        };

        const systemTheme = detectSystemTheme();
        set({ systemTheme });

        // 监听系统主题变化
        if (window.matchMedia) {
          const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
          mediaQuery.addEventListener('change', (e) => {
            const newSystemTheme = e.matches ? 'dark' : 'light';
            set({ systemTheme: newSystemTheme });
            
            // 如果当前主题是auto，则应用新的系统主题
            if (get().theme === 'auto') {
              applyTheme(newSystemTheme);
            }
          });
        }

        // 应用初始主题
        const effectiveTheme = get().theme === 'auto' ? systemTheme : get().theme;
        applyTheme(effectiveTheme);
      },
    }),
    {
      name: 'theme-storage',
      partialize: (state) => ({ theme: state.theme }),
    }
  )
);

// 应用主题到CSS变量
function applyTheme(theme: 'light' | 'dark') {
  const root = document.documentElement;
  const themeConfig = THEMES[theme];
  
  if (themeConfig && themeConfig.colors) {
    Object.entries(themeConfig.colors).forEach(([key, value]) => {
      root.style.setProperty(`--color-${key}`, value);
    });
  }

  // 设置主题类名
  root.setAttribute('data-theme', theme);
}

// 获取CSS变量值
export function getThemeColor(colorName: string): string {
  return getComputedStyle(document.documentElement)
    .getPropertyValue(`--color-${colorName}`)
    .trim();
}